<template>
  <div class="calendar-detail-container">
    <!-- 日历头部 -->
    <div class="calendar-header">
      <div class="calendar-title">
        <h3>{{ currentSemesterName }} - 周日历</h3>
        <div class="calendar-controls">
          <el-button-group>
            <el-button size="mini" @click="previousWeek">上一周</el-button>
            <el-button size="mini" @click="currentWeek">本周</el-button>
            <el-button size="mini" @click="nextWeek">下一周</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="week-display">
        {{ formatWeekRange(currentWeekRange) }}
      </div>
    </div>

    <!-- 日历主体 -->
    <div class="calendar-body">
      <div class="time-slots">
        <div class="time-header">时间</div>
        <div class="time-slot" v-for="period in timeSlots" :key="period.id">
          {{ period.label }}
        </div>
      </div>
      
      <div class="calendar-grid" ref="calendarGrid">
        <div class="day-column" v-for="day in weekDays" :key="day.date">
          <div class="day-header" :class="{ today: day.isToday }">
            <div class="day-name">{{ day.name }}</div>
            <div class="day-date">{{ day.dateLabel }}</div>
          </div>
          
          <div class="day-courses">
            <div 
              class="course-item" 
              v-for="course in getDayCourses(day.date, period.id)" 
              :key="course.id"
              :class="{ 'empty-slot': !course, 'has-course': course }"
              @click="handleCourseClick(course, day.date, period.id)"
            >
              <div v-if="course" class="course-content">
                <div class="course-name">{{ course.courseName }}</div>
                <div class="course-info">{{ course.teacherName }} - {{ course.classroomName }}</div>
                <div class="course-class">{{ course.className }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程详情弹窗 -->
    <el-dialog
      :title="courseDetailTitle"
      :visible.sync="detailDialogVisible"
      width="500px"
      class="course-detail-dialog"
    >
      <div class="course-detail-content" v-if="selectedCourse">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="课程名称">{{ selectedCourse.courseName }}</el-descriptions-item>
          <el-descriptions-item label="上课时间">{{ selectedCourse.time }}</el-descriptions-item>
          <el-descriptions-item label="上课地点">{{ selectedCourse.classroomName }}</el-descriptions-item>
          <el-descriptions-item label="任课教师">{{ selectedCourse.teacherName }}</el-descriptions-item>
          <el-descriptions-item label="上课班级">{{ selectedCourse.className }}</el-descriptions-item>
          <el-descriptions-item label="课程类型">{{ selectedCourse.courseType }}</el-descriptions-item>
          <el-descriptions-item label="周次范围">{{ selectedCourse.weekRange }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ selectedCourse.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 使用原生Date方法替代date-fns，避免webpack兼容性问题

export default {
  name: 'CalendarDetail',
  props: {
    scheduleData: {
      type: Array,
      default: () => []
    },
    semesterName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentWeekStart: new Date(),
      timeSlots: [
        { id: 1, label: '第1节 (8:00-8:45)' },
        { id: 2, label: '第2节 (8:55-9:40)' },
        { id: 3, label: '第3节 (10:00-10:45)' },
        { id: 4, label: '第4节 (10:55-11:40)' },
        { id: 5, label: '第5节 (14:00-14:45)' },
        { id: 6, label: '第6节 (14:55-15:40)' },
        { id: 7, label: '第7节 (16:00-16:45)' },
        { id: 8, label: '第8节 (16:55-17:40)' }
      ],
      selectedCourse: null,
      detailDialogVisible: false,
      courseDetailTitle: ''
    }
  },
  computed: {
    currentSemesterName() {
      return this.semesterName || '当前学期'
    },
    currentWeekRange() {
      const start = this.getStartOfWeek(this.currentWeekStart)
      const end = this.getEndOfWeek(this.currentWeekStart)
      return { start, end }
    },
    weekDays() {
      const days = []
      const start = this.getStartOfWeek(this.currentWeekStart)
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(start)
        date.setDate(start.getDate() + i)
        days.push({
          date: this.formatDate(date, 'yyyy-MM-dd'),
          name: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][i],
          dateLabel: this.formatDate(date, 'MM-dd'),
          isToday: this.isToday(date)
        })
      }
      return days
    }
  },
  methods: {
    /** 获取某天的课程 */
    getDayCourses(date, periodId) {
      return this.scheduleData.filter(course => 
        course.date === date && course.period === periodId
      )
    },
    
    /** 获取周开始日期 */
    getStartOfWeek(date) {
      const d = new Date(date)
      const day = d.getDay()
      const diff = d.getDate() - day + (day === 0 ? -6 : 1)
      d.setDate(diff)
      d.setHours(0, 0, 0, 0)
      return d
    },
    
    /** 获取周结束日期 */
    getEndOfWeek(date) {
      const d = this.getStartOfWeek(date)
      d.setDate(d.getDate() + 6)
      d.setHours(23, 59, 59, 999)
      return d
    },
    
    /** 格式化日期 */
    formatDate(date, format) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      
      if (format === 'yyyy-MM-dd') {
        return `${year}-${month}-${day}`
      } else if (format === 'MM-dd') {
        return `${month}-${day}`
      } else if (format === 'yyyy年MM月dd日') {
        return `${year}年${month}月${day}日`
      }
      return `${year}-${month}-${day}`
    },
    
    /** 检查是否为今天 */
    isToday(date) {
      const today = new Date()
      return date.toDateString() === today.toDateString()
    },
    
    /** 上一周 */
    previousWeek() {
      const newDate = new Date(this.currentWeekStart)
      newDate.setDate(newDate.getDate() - 7)
      this.currentWeekStart = newDate
      this.$emit('week-change', this.currentWeekRange)
    },
    
    /** 下一周 */
    nextWeek() {
      const newDate = new Date(this.currentWeekStart)
      newDate.setDate(newDate.getDate() + 7)
      this.currentWeekStart = newDate
      this.$emit('week-change', this.currentWeekRange)
    },
    
    /** 本周 */
    currentWeek() {
      this.currentWeekStart = new Date()
      this.$emit('week-change', this.currentWeekRange)
    },
    
    /** 格式化周范围 */
    formatWeekRange(range) {
      return `${this.formatDate(range.start, 'yyyy年MM月dd日')} - ${this.formatDate(range.end, 'yyyy年MM月dd日')}`
    },
    
    /** 点击课程 */
    handleCourseClick(course, date, period) {
      if (!course) return
      
      this.selectedCourse = course
      this.courseDetailTitle = `${course.courseName} - ${format(new Date(date), 'MM月dd日')} ${this.timeSlots.find(s => s.id === period)?.label || ''}`
      this.detailDialogVisible = true
    }
  }
}
</script>

<style scoped>
.calendar-detail-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  margin-bottom: 20px;
}

.calendar-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.calendar-title h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.week-display {
  color: #666;
  font-size: 14px;
}

.calendar-body {
  display: flex;
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.time-slots {
  width: 120px;
  border-right: 1px solid #ebeef5;
  background: #f5f7fa;
}

.time-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
  background: #409eff;
  color: white;
}

.time-slot {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #666;
  border-bottom: 1px solid #ebeef5;
  padding: 5px;
  text-align: center;
}

.calendar-grid {
  display: flex;
  min-width: 700px;
}

.day-column {
  flex: 1;
  min-width: 100px;
  border-right: 1px solid #ebeef5;
}

.day-column:last-child {
  border-right: none;
}

.day-header {
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
}

.day-header.today {
  background: #ecf5ff;
}

.day-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.day-date {
  font-size: 12px;
  color: #666;
}

.day-courses {
  display: flex;
  flex-direction: column;
}

.course-item {
  height: 80px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.course-item:hover {
  background: #f5f7fa;
}

.course-item.empty-slot {
  background: #fafafa;
}

.course-item.has-course {
  background: #ecf5ff;
  border: 1px solid #b3d8ff;
}

.course-content {
  padding: 8px;
  text-align: center;
  font-size: 12px;
}

.course-name {
  font-weight: bold;
  color: #409eff;
  margin-bottom: 2px;
}

.course-info {
  color: #666;
  margin-bottom: 2px;
}

.course-class {
  color: #909399;
}

.course-detail-dialog .el-dialog__body {
  padding: 20px;
}

.course-detail-content {
  max-height: 400px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .calendar-body {
    overflow-x: scroll;
  }
  
  .calendar-grid {
    min-width: 800px;
  }
  
  .time-slots {
    width: 80px;
  }
  
  .time-slot {
    font-size: 10px;
  }
}
</style>